package com.lkk.cg.base;

import com.lkk.cg.util.PageBean;
import com.lkk.cg.util.QueryHelper;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by lkk on 2014/11/25.
 */
@Transactional
@SuppressWarnings("unchecked")
public class DaoSupportImpl<T> implements DaoSupport<T> {

    @Resource
    SessionFactory sessionFactory;

    protected Class<T> clazz = null;

    /**
     * 如果不提供持久化类的类型，使用默认的检测方式
     */
    public DaoSupportImpl() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[0];
    }

    /**
     * 手动指定持久化类型，该构造方法主要用于测试
     *
     * @param clazz          持久化类的Class对象
     * @param sessionFactory 对象工厂
     */
    public DaoSupportImpl(Class<T> clazz, SessionFactory sessionFactory) {
        this.clazz = clazz;
        this.sessionFactory = sessionFactory;
    }

    public T getById(Long id) {
        return (T) getSession().get(clazz, id);
    }

    public void delete(Long id) {
        getSession().delete(getById(id));
    }

    public void save(T entity) {
        getSession().save(entity);
    }

    public void update(T entity) {
        getSession().update(entity);
    }

    public List<T> getAll() {
        return getSession().createQuery("from " + clazz.getSimpleName())
                .list();
    }

    public List<T> getByIds(Long[] ids) {

        return getSession().createQuery("from " + clazz.getSimpleName() + " e where e.id in (:ids)")
                .setParameterList("ids", ids)
                .list();
    }

    // 公共的查询分页信息的方法
    public PageBean getPageBean(int pageNum, int pageSize, QueryHelper queryHelper) {

        // 参数列表
        List<Object> parameters = queryHelper.getParameters();

        // 查询本页的数据列表
        Query listQuery = getSession().createQuery(queryHelper.getListQueryHql()); // 创建查询对象
        if (parameters != null) { // 设置参数
            for (int i = 0; i < parameters.size(); i++) {
                listQuery.setParameter(i, parameters.get(i));
            }
        }
        listQuery.setFirstResult((pageNum - 1) * pageSize);
        listQuery.setMaxResults(pageSize);
        List list = listQuery.list(); // 执行查询

        // 查询总记录数量
        Query countQuery = getSession().createQuery(queryHelper.getCountQueryHql());
        if (parameters != null) { // 设置参数
            for (int i = 0; i < parameters.size(); i++) {
                countQuery.setParameter(i, parameters.get(i));
            }
        }
        Long count = (Long) countQuery.uniqueResult(); // 执行查询

        return new PageBean(pageSize,pageNum, count.intValue(), list);
    }


    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }
}
